package com.qd.p2p.web.action.borrow;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;

import com.opensymphony.xwork2.ModelDriven;
import com.qdlc.p2p.biz.service.AccountService;
import com.qdlc.p2p.biz.service.BorrowAutoService;
import com.qdlc.p2p.biz.service.UserIdentifyService;
import com.qdlc.p2p.biz.tpp.TppBaseInterface;
import com.qdlc.p2p.biz.tpp.TppServiceFactory;
import com.qdlc.p2p.biz.web.action.BaseAction;
import com.qdlc.p2p.common.constant.Constant;
import com.qdlc.p2p.common.exception.BorrowException;
import com.qdlc.p2p.common.exception.BusinessException;
import com.qdlc.p2p.dal.checkrule.AutoTenderConfRuleCheck;
import com.qdlc.p2p.dal.common.RuleCheckHelper;
import com.qdlc.p2p.dal.dto.Account;
import com.qdlc.p2p.dal.dto.BorrowAuto;
import com.qdlc.p2p.dal.dto.User;
import com.qdlc.p2p.dal.dto.UserCache;
import com.qdlc.p2p.dal.dto.UserIdentify;
import com.qdlc.p2p.dal.model.BorrowAutoModel;
import com.qdlc.p2p.dal.model.TppModel;
import com.qdlc.p2p.dal.util.UserTypeUtils;
import com.qdlc.p2p.dal.util.UserUtils;

/**
 * 自动投标
 * @author zf
 * @version 2.0
 * @since 2014年11月14日
 */
public class BorrowAutoAction extends BaseAction<BorrowAutoModel> implements ModelDriven<BorrowAutoModel> {

	@Resource
	private BorrowAutoService borrowAutoService;
	@Resource
	private AccountService accountService;
	@Resource
	private UserIdentifyService userIdentifyService;
	
	private User user;

	/**
	 * 我的自动投标设置
	 * 
	 * @return
	 */
	@Action("/member/auto/detail")
	public String detail() throws Exception {
		user = getSessionUser();
		checkInvestUser();
		Account account = accountService.findAccountByUserId(user.getUserId());
		BorrowAuto auto = borrowAutoService.init(user);
		request.setAttribute("auto", auto);
		request.setAttribute("account", account);
		List<Integer> list = new ArrayList<Integer>();
		for (int i=0; i<= 12; i++) {
			list.add(i);
		}
		request.setAttribute("list", list);
		UserCache userCache = UserUtils.getUserCacheByUserId(user);
		request.setAttribute("isImp", userCache.getIsImp());
		return "detail";
	}
	//我的自动投标设置 3类型
//	@Action("/member_borrow/auto/detail")
//	public String borrowDetail() throws Exception {
//
//		user = getSessionUser();
//		checkInvestUser();
//		Account account = accountService.findByUser(user.getUserId());
//		BorrowAuto auto = borrowAutoService.init(user);
//		request.setAttribute("auto", auto);
//		request.setAttribute("account", account);
//		List<Integer> list = new ArrayList<Integer>();
//		for (int i=0; i<= 12; i++) {
//			list.add(i);
//		}
//		request.setAttribute("list", list);
//		return "detail";
//	}

	/**
	 * 修改自动投标设置
	 * 如果是从关闭到开启，那么需要跳转到第三方处理业务
	 * @return
	 */
	@Action(value="/member/auto/modify", results = { @Result(name="autoTender", type = "ftl", location="/member/tpp/"+Constant.TPP_PACKAGE+"/autoTender.html"),
			@Result(name="success", type = "redirect", location="/member/auto/detail.html"),
			@Result(name="borrow_success", type = "redirect", location="/member_borrow/auto/detail.html")})
	public String modify() throws Exception {
		User u = getSessionUser();
		BorrowAuto a = borrowAutoService.findByUser(u);
		BorrowAuto auto = model.prototype();
		auto.setAddTime(a.getAddTime());
		auto.setAddIp(a.getAddIp());
		auto.setUser(u);
		auto.setUpdateTime(a.getUpdateTime());
		if (!a.getEnable()) {
			//开启自动投标需要先校验是否实名以及是否在双乾授权
			UserIdentify userIdentify = userIdentifyService.findByUserId(u.getUserId());
			model.validBorrowAutoOpen(userIdentify);
			auto.setEnable(a.getEnable());
			borrowAutoService.update(auto);
			TppModel tppModel = new TppModel();
			tppModel.setUser(a.getUser());
			tppModel.setAutoTenderId(a.getId());
			TppBaseInterface tppService = TppServiceFactory.newIntance();
			Object autoTender = tppService.tppAutoTenderPlan(tppModel);
			request.setAttribute("autoTender", autoTender);
			return "autoTender";
		}else{
			borrowAutoService.update(auto);
		}
		if(UserTypeUtils.isInvestor(u.getUserId()))
			return "success";
		else
			return "borrow_success";
	}

	/**
	 * 修改自动投标状态
	 * 
	 * @return
	 */
	@Action("/member/auto/modifyStatus")
    public void modifyStatus() throws Exception {
        String msg = "";
        boolean result = true;
        if (model.getEnable()) {
            Account account = accountService.findAccountByUserId(getSessionUserId());
            AutoTenderConfRuleCheck autoTenderConf = RuleCheckHelper.getValue(AutoTenderConfRuleCheck.class);
            // 开启自动投标不能小于最小可用余额
            double minUseMoney = autoTenderConf.auto_tender_min_usemoney;
            if (account.getUseMoney() < minUseMoney) {
                throw new BorrowException("账户可用余额最少为" + minUseMoney + "元才能体验自动投资", BusinessException.TYPE_JSON);
            }
        } else {
            User u = getSessionUser();
            BorrowAuto auto = borrowAutoService.findByUser(u);
            if (auto.getEnable()) {
                //-- 自动投标关闭
                TppModel tppModel = new TppModel();
                tppModel.setUser(u);
                tppModel.setAutoTenderId(auto.getId());
                TppBaseInterface tppService = TppServiceFactory.newIntance();
                boolean isClose = tppService.tppCloseAutoTenderPlan(tppModel);
                if (!isClose) {
                    result = false;
                    msg = "设置失败,请重试!";
                    printWebResult(msg, result);
                    return;
                }
            }
            printWebResult("已关闭自动投标", result);
            return;
        }
        printWebResult(msg, result);
    }

    @Action(value="/member/auto/autoClose", results = { @Result(name="success", type = "ftl", location="/member/tpp/"+Constant.TPP_PACKAGE+"/autoTenderClose.html")})
	public String autoClose() throws Exception {
		User u = getSessionUser();
		if(u==null){
			throw new BorrowException("用户不能为空！", BusinessException.TYPE_JSON);
		}
		BorrowAuto auto = borrowAutoService.findByUser(u);
		if(auto==null){
			throw new BorrowException("自动投标关闭失败！", BusinessException.TYPE_JSON);
		}
		//-- 自动投标关闭
		TppModel tppModel = new TppModel();
		tppModel.setUser(u);
		tppModel.setAutoTenderId(auto.getId());
		TppBaseInterface tppService = TppServiceFactory.newIntance();
		Object tpClose = tppService.tppCloseAutoTenderPlan(tppModel);
		request.setAttribute("autoTenderClose", tpClose);
		return "success";
	}

}
